前言:
頁面功能差不多都完成之後,可以使用推播通知來提醒時間
正文:
以下採用設定時間來推播
func notification() {
UNUserNotificationCenter.current().removeAllDeliveredNotifications()
for result in orders {
if result.SwitchOrder {
let content = UNMutableNotificationContent()
content.title = "鬧鐘提醒"
content.subtitle = "現在時刻"
content.body = "\(result.TimeOrder)"
//content.badge = 1
content.sound = UNNotificationSound.default
let date = Date()
let calendar = Calendar.current
var components = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second],
from: date)
components.year = Calendar.current.component(.year, from: Date())
components.month = Calendar.current.component(.month, from: Date())
components.day = Calendar.current.component(.day, from: Date())
var subString = (result.TimeOrder as NSString).substring(with: NSMakeRange(0,2))
components.hour = Int(subString)
subString = (result.TimeOrder as NSString).substring(with: NSMakeRange(3,2))
components.minute = Int(subString)
components.second = 0
let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: false)
let request = UNNotificationRequest(identifier: result.id , content: content, trigger: trigger)
print(date)
print(components)
print("=================================================")
UNUserNotificationCenter.current().add(request, withCompletionHandler: {error in
print("成功建立通知...")
})
}
}
}
成果圖: